﻿using PetaPoco;
using YMJF_Service.Models;
using YMJF_Service.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Text;
using HMACAuthentication.WebApi.Filters;

namespace YMJF_Service.Controllers
{
    /// <summary>
    /// 字典管理
    /// </summary>
    [RoutePrefix("api/dict")]
    public class DictController : ApiController
    {
        ConnectionStringMySQLDB db = new ConnectionStringMySQLDB();

        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pagesize">每页行数</param>
        /// <param name="sort">排序字段</param>
        /// <param name="order">排序方式</param>
        /// <returns></returns>
        [HttpGet]
        [Route("Dicts")]
        public ApiResult GetDictList(long page, long pagesize, string sort, string order)
        {
            ApiResult res = new ApiResult();
            try
            {
                string sqlwhere = "";
                string sqlorder = " order by " + sort + " " + order;
                Page<object> list = db.Page<object>(page, pagesize, @" select * from ( SELECT * FROM dictionary where  SysDeleted = 0 " + sqlwhere + " ) t " + sqlorder);
                res.code = HttpCode.success;
                res.message = "获取字典列表成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取字典列表错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 获取字典详细
        /// </summary>
        /// <param name="code">字典类型代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("Dicts")]
        public ApiResult GetDict(string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                dictionary data = db.FirstOrDefault<dictionary>("WHERE DictCode=@0", code);
                if (data != null)
                {
                    res.code = HttpCode.success;
                    res.message = "获取字典详细成功";
                    res.data = data;
                }
                else
                {
                    res.code = HttpCode.Que_Failed;
                    res.message = "获取字典详细失败";
                }
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取字典详细异常：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="data">字典信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Dict")]
        [HMACAuthenticationAttribute]
        public ApiResult AddDict(dictionary data)
        {
            ApiResult res = new ApiResult();
            try
            {
                string user = "admin";
                data.IfAllow = true;
                data.SysCreatedBy = user;
                data.SysCreate = DateTime.Now;
                data.SysLastUpdBy = user;
                data.SysLastUpd = DateTime.Now;
                data.SysDeleted = false;
                object obj = data.Insert();
                if (obj != null)
                {
                    res.code = HttpCode.success;
                    res.message = "添加成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "添加失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "添加字典错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }

        /// <summary>
        /// 修改字典
        /// </summary>
        /// <param name="data">字典信息</param>
        /// <returns></returns>
        [HttpPatch]
        [Route("Dict")]
        [HMACAuthenticationAttribute]
        public ApiResult UpdateDict(dictionary data)
        {
            ApiResult res = new ApiResult();
            try
            {
                // Dictionary.SingleOrDefault(data.DictCode);
                string user = "admin";
                data.SysLastUpdBy = user;
                data.SysLastUpd = DateTime.Now;
                data.SysDeleted = false;
                object obj = data.Update();
                if (obj != null)
                {
                    res.code = HttpCode.success;
                    res.message = "修改成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "修改失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL( "dict", "修改字典错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 删除字典
        /// </summary>
        /// <param name="code">字典类型代码</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("Dict/{code}")]
        public ApiResult DelDict(string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                string sql = string.Format("update dictionary  SET SysDeleted = 1 where DictCode='{0}'", code);
                int ret = db.Execute(sql);
                if (ret > 0)
                {
                    res.code = HttpCode.success;
                    res.message = "删除字典成功";
                }
                else
                {
                    res.code = HttpCode.Del_Failed;
                    res.message = "删除字典失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "删除字典异常：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }


        /// <summary>
        /// 获取某字典下选项列表(分页)
        /// </summary>
        /// <param name="code">字典代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("DictItems")]
        public ApiResult GetDictItemsList(long page, long pagesize,string sort,string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                Page<dictionarydetail> list = dictionarydetail.Page(page,pagesize,@"  where  SysDeleted = 0 and DictCode = @0  order by SerialNumber  ", code);
                res.code = HttpCode.success;
                res.message = "获取字典列表成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取某字典下选项列表错误：" + code + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 获取父字典下选项列表
        /// </summary>
        /// <param name="fcode">字典代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("ItemsForFCode")]
        public ApiResult GetFItemList(string fcode)
        {
            ApiResult res = new ApiResult();
            try
            {
                List<dictionarydetail> list = dictionarydetail.Fetch(@"  where  SysDeleted = 0 and PItemCode = @0  order by SerialNumber  ", fcode);
                res.code = HttpCode.success;
                res.message = "获取父字典下选项列表成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取获取父字典下选项列表错误：" + fcode + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }
       
        /// <summary>
        /// 获取某字典下选项列表
        /// </summary>
        /// <param name="code">字典代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("Items")]
        public ApiResult GetItemList(string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                List<dictionarydetail> list = dictionarydetail.Fetch(@"  where  SysDeleted = 0 and DictCode = @0  order by SerialNumber  ", code);
                res.code = HttpCode.success;
                res.message = "获取字典列表成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取某字典下选项列表错误：" + code + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        /// <summary>
        ///  获取某字典下选项列表2
        /// </summary>
        /// <param name="code">字典代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("Items2")]
        public ApiResult GetItemList2(string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                StringBuilder builder = new StringBuilder();
                Dictionary<string, List<dictionarydetail>> data = new Dictionary<string, List<Models.dictionarydetail>>();
                if (code.Contains(','))
                {
                    string[] codeList = code.Split(',');
                    foreach (var item in codeList)
                    {
                        List<dictionarydetail> list = dictionarydetail.Fetch(@"  where  SysDeleted = 0 and DictCode = @0  order by SerialNumber  ", item);
                        data.Add(item, list);
                    }
                }

                res.code = HttpCode.success;
                res.message = "获取字典列表成功";
                res.data = data;

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取某字典下选项列表2错误：" + code + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }


       


        /// <summary>
        /// 添加字典项
        /// </summary>
        /// <param name="data">字典项信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("DictItem")]
        [HMACAuthenticationAttribute]
        public ApiResult AddDictItem(dictionarydetail data)
        {
            ApiResult res = new ApiResult();
            try
            {
                string user = "admin";
                data.DetailId = Guid.NewGuid().ToString();
                data.IfEnabled = true;
                data.SysCreatedBy = user;
                data.SysCreate = DateTime.Now;
                data.SysLastUpdBy = user;
                data.SysLastUpd = DateTime.Now;
                data.SysDeleted = false;
                object obj = data.Insert();
                if (obj != null)
                {
                    res.code = HttpCode.success;
                    res.message = "添加成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "添加失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL( "dict", "添加字典项错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }

        /// <summary>
        /// 获取字典项详细
        /// </summary>
        /// <param name="ID">字典明细主键ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("DictItems")]
        public ApiResult GetDictItems(string ID)
        {
            ApiResult res = new ApiResult();
            try
            {
                dictionarydetail data = db.FirstOrDefault<dictionarydetail>("WHERE DetailId=@0", ID);
                if (data != null)
                {
                    res.code = HttpCode.success;
                    res.message = "获取字典项详细成功";
                    res.data = data;
                }
                else
                {
                    res.code = HttpCode.Que_Failed;
                    res.message = "获取字典项详细失败";
                }
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", "获取字典项详细异常：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }


        /// <summary>
        /// 删除字典项
        /// </summary>
        /// <param name="ID">字典明细主键ID</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("DictItems/{ID}")]
        public ApiResult DelDictItem(string ID)
        {
            ApiResult res = new ApiResult();
            try
            {
                string sql = string.Format("update dictionarydetail  SET SysDeleted = 1 where DetailId='{0}'", ID);
                int ret = db.Execute(sql);
                if (ret > 0)
                {
                    res.code = HttpCode.success;
                    res.message = "删除字典项成功";
                }
                else
                {
                    res.code = HttpCode.Del_Failed;
                    res.message = "删除字典项失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("dict", " 删除字典项异常：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }

    }
}